package partner_middleware

import (
	"gitee.com/theegg/go-brick/app/modules/partner_api"
	"gitee.com/theegg/go-brick/app/service/app"
	"gitee.com/theegg/go-brick/app/service/help/carray"
	"github.com/gin-gonic/gin"
	"strings"
)

var IgnorePermissionRoute = []string{"/ppi/admin/baseInfo"}

// 检测用户是否具有指定的路径权限
func PartnerAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		if method == "OPTIONS" {
			c.Next()
			return
		}

		currentPau := partner_api.GetLoginPartnerAdminUser(c)

		// 用户是否已经登陆
		if currentPau.Id == 0 {
			app.NewResponse(c).ErrorReturn(app.UnauthorizedAuthNotExist)
			c.Abort()
			return
		}

		// 跳过 忽略权限 的路径
		path := c.FullPath()
		if carray.IsStringInArray(path, IgnorePermissionRoute) {
			c.Next()
			return
		}

		// 获取权限
		permissions, err := currentPau.GetUserAllowedPermissions()
		if err != nil {
			app.NewResponse(c).ErrorReturn(app.UnauthorizedNotAuth)
			c.Abort()
			return
		}

		if item, ok := permissions[path]; ok {
			methods := strings.Split(item.HttpMethod, ",")
			if len(methods) == 0 {
				app.NewResponse(c).ErrorReturn(app.MethodNotAllowed)
				c.Abort()
				return
			}

			// 检测http Methods
			for _, v := range methods {
				if method == v {
					c.Set("c_api_error_lang", currentPau.Lang)
					c.Next()
					return
				}
			}

			app.NewResponse(c).ErrorReturn(app.RouteNotAllowed)
			c.Abort()
			return
		}

		app.NewResponse(c).ErrorReturn(app.RouteNotAllowed)
		c.Abort()
		return
	}
}
